<template>
	<div>
		<div class="container">
			<div class="handle-box">
				
				<el-input v-model="query.userName" placeholder="用户名称/id" class="handle-input mr10"></el-input>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
			</div>
			<!-- :data 绑定的是需要渲染的数据列表 -->
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
				<el-table-column prop="userName" label="用户名"></el-table-column>
				<el-table-column  label="头像(查看大图)" align="center" width="100%">
					<template #default="scope">
						<el-image
							class="table-td-thumb"
							:src="getImageUrl(scope.row.avator)"
							:z-index="10"
							style="width: 100px; height: 100px"
							:preview-src-list="[scope.row.avator]"
							fit="fill"
							preview-teleported
						>
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="phoneNum" label="手机号"></el-table-column>
				<el-table-column prop="sex" label="性别"></el-table-column>
				<el-table-column prop="introduction" width="220" label="个人介绍" ></el-table-column>
				<el-table-column prop="birth" label="出生日期"></el-table-column>
		        <el-table-column prop="address" label="地址"></el-table-column>
				<!-- <el-table-column label="状态" align="center">
					<template #default="scope">
						<el-tag
							:type="scope.row.state === '成功' ? 'success' : scope.row.state === '失败' ? 'danger' : ''"
						>
							{{ scope.row.state }}
						</el-tag>
					</template>
				</el-table-column> -->
				<el-table-column label="操作" width="120" align="center">
					<template #default="scope" >
						<el-button text :icon="Edit" 
							@click="handleEdit(scope.$index, scope.row)" >
							编辑
						</el-button>
						<el-button text :icon="Delete" class="red" 
							@click="handleDelete(scope.row)" >
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 current-page、page-size（每页条数）、total（总条数） -->
			<div class="pagination">
				<el-pagination
					background
					layout="total, prev, pager, next"
					:current-page="query.pageNum"
					:page-size="query.pageSize"
					:total="pageTotal"
					@current-change="handlePageChange"
				></el-pagination>
			</div>
		</div>

		<!-- 编辑弹出框 -->
		<el-dialog :title="dialogTitle" v-model="editVisible" width="80%">
			<el-form label-width="70px">
				<el-form-item label="用户名">
					<el-input v-model="form.userName"></el-input>
				</el-form-item>
				<el-form-item label="密码">
					<el-input v-model="form.userPwd"></el-input>
				</el-form-item>
				<el-form-item label="手机号">
					<el-input v-model="form.phoneNum"></el-input>
				</el-form-item>
				<el-form-item label="性别" prop="region">
					<el-select v-model="form.sex" placeholder="请选择">
						<el-option key="男" label="男" value="bbk"></el-option>
						<el-option key="女" label="女" value="xtc"></el-option>
						
					</el-select>
				</el-form-item>
				<!-- 头像上传  -->
				<el-form-item label="头像">
					<el-upload  style="display: display;"
						class="avatar-uploader"
						action="http://localhost:8080/upload/image"
						:show-file-list="false"
						
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
						>
						<img v-if="form.avator" :src="getImageUrl(form.avator) " class="avatar" />
						<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>					
					</el-upload>

				</el-form-item>
				<el-form-item label="个人介绍" :formatter="getIntroduction">
					<el-input v-model="form.introduction" type="textarea" :rows="5"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveEdit">确 定</el-button>
					
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox, formItemValidateStates } from 'element-plus';
import { Delete, Edit, Search, Plus, List } from '@element-plus/icons-vue';
import { fetchData } from '../api/index';
import type { UploadProps } from 'element-plus'

import { getImageUrl } from '../utils/index';
import http from '../utils/request'

interface TableItem {
	id: number;
	userName: string;
	avator: string;
	userPwd:'',
	sex:'',
	phoneNum:'',
	birth:'',
	address: '',
	introduction: string;
}

const query = reactive({
	address: '',
	userName: '',	//歌单名称/风格
	pageNum: 1,
	pageSize: 10
});


//要显示的数据
const tableData = ref<TableItem[]>([

]);
// List<User> list = new List<User>();
// list.add(Student);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
	// fetchData().then(res => {
	// 	tableData.value = res.data.list;
	// 	pageTotal.value = res.data.pageTotal || 50;
	// });
	http.get("/admin/user", {
		params: query
	}).then((res: any) => {
		console.log('获取用户信息 res = ', res)
		tableData.value = res.data.data.list;
		pageTotal.value = res.data.data.total;	//
	}).catch((err: any) => {
		console.log('获取用户信息 res = ', err)
	})
};

getData();

// 查询操作
const handleSearch = () => {
	query.pageNum = 1;
	getData();
};
// 分页导航
const handlePageChange = (val: number) => {
	query.pageNum = val;
	getData();
};

const uploadRef = ref('');

//头像上传
const imageUrl = ref('')


//上传文件前回调该方法，用于校验文件格式、大小；
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('beforeAvatarUpload = ', rawFile);
//   if (rawFile.type == 'image/jpeg') {
//     ElMessage.error('Avatar picture must be JPG format!')
//     return false
//   } else if (rawFile.size / 1024 / 1024 > 2) {
//     ElMessage.error('Avatar picture size can not exceed 2MB!')
//     return false
//   }
//   return true
}

//上传成功：会请求 action 属性配置的URL，成功后回调该方法；
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
	//这里
  console.log('handleAvatarSuccess = ', response, ' uploadFile = ',uploadFile);
  if("200" === response.code){
	// form.pic = URL.createObjectURL(uploadFile.raw!)
	form.avator = response.url;//成功后将服务器返回的 url 赋值给 form.pic
  }
}
// 删除操作
const handleDelete = (row: any) => {
	// 二次确认删除
	ElMessageBox.confirm(`确定要删除用户【${row.userName}】吗？`, '提示', {
		type: 'warning'
	})
	.then(() => {//用户点击确定按钮
		http.delete("/admin/user/" + row.id)
		.then((res) => {
			console.log('删除返回值：', res);
			if(res.data.code === 200){	//修改成功
				ElMessage.success(`删除成功`);
				getData();
			}
		}).catch((err) => {
			console.log('删除失败：', err);
			ElMessage.error(`删除失败`);
		});
	})
	.catch(() => {//点击取消按钮

	});
};

// 表格编辑时弹窗和保存
const dialogTitle = ref('新增');
const editVisible = ref(false);
let form = reactive({
	id: '',
	userName: '',
	userPwd:'',
	sex:'',
	phoneNum:'',
	birth:'',
	avator: '',
	introduction: '',
	address: ''
});
const handleAdd = () => {
	dialogTitle.value = "新增";
	form.id = '';
	form.userName = '';
	form.userPwd = '',
	form.phoneNum = '',
	form.birth = '',
	form.avator = '';
	form.address = '',
	form.introduction = '';
	editVisible.value = true;
};
const handleEdit = (index: number, row: any) => {
	dialogTitle.value = "编辑";
	form.id = row.id;
	form.userName = row.userName;
	form.userPwd = row.userPwd;
	form.phoneNum = row.phoneNum;
	form.birth = row.birth;
	form.avator = row.avator;
	form.address=row.address;
	form.introduction = row.introduction;
	editVisible.value = true;
};
const saveEdit = () => {
	// ElMessage.success(`修改第 ${idx + 1} 行成功`);
	// tableData.value[idx].name = form.name;
	// tableData.value[idx].address = form.address;
	if(!form.id){	//form.id 为空：新增
		console.log('新增', form);
		http.post("/admin/user/user", form)
		.then((res) => {
			console.log('新增返回值：', res);
			if(res.data.code === 200){	//新增成功
				ElMessage.success(`新增成功`);
				editVisible.value = false;
				getData();
			}
		}).catch((err) => {
			console.log('新增失败：', err);
			ElMessage.error(`新增失败`);
		});
	}else{ //修改
		console.log('修改', form);
		http.put("/admin/user/info", form)
		.then((res) => {
			console.log('修改返回值：', res);
			if(res.data.code === 200){	//修改成功
				ElMessage.success(`修改成功`);
				editVisible.value = false;
				getData();
			}
		}).catch((err) => {
			console.log('修改失败：', err);
			ElMessage.error(`修改失败`);
		});
	}
};

// row(行对象), column（列对象）, cellValue（当前单元格内容，简介）, index（下标）
const getIntroduction = (row: any, column: any, cellValue: any, index: any) => {
	console.log("格式化简介内容", row, column, cellValue.length, index);
	if(cellValue.length > 50){
		return cellValue.substr(0, 50) + '...';
	}
	return cellValue;
}

// const getImageUrl = (picUrl: any) => {
// 	return "http://localhost:8080" + picUrl;
// }

</script>

<style scoped>
.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}
.table {
	width: 100%;
	font-size: 14px;
}
.red {
	color: #ff0000;
}
.mr10 {
	margin-right: 10px;
}
.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}

.el-upload {
  width: 178px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
